package com.java.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.java.business.system.permis.bean.User;
import com.java.core.bean.ResultBean;
import com.java.core.utils.ResponseUtils;
import com.java.core.utils.SessionUtils;

/**
 * 请求过滤器
 * 
 * @author W.G
 * 
 */
public class RequestFilter implements Filter {
	// 过滤请求标识，防止多次请求
	private static final String FILTERED_REQUEST = "@@session_context_filtered_request";
	// ① 不需要登录即可访问的URI资源
	private static final String[] INHERENT_ESCAPE_URIS = { "/login.do",
			"login.jsp" };

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// ②-1 保证该过滤器在一次请求中只被调用一次
		if (request.getAttribute(FILTERED_REQUEST) != null) {
			chain.doFilter(request, response);
		} else {
			// ②-2 设置过滤标识，防止一次请求多次过滤
			request.setAttribute(FILTERED_REQUEST, Boolean.TRUE);
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			// 获取SessionUser
			// ②-3 用户未登录, 且当前URI资源需要登录才能访问
			User user = SessionUtils.getSessionUser(httpRequest);// 登录的用户信息
			if (user == null
					&& !isURILogin(httpRequest.getRequestURI(), httpRequest)) {
				// 判断是否AJAX请求
				if ("XMLHttpRequest".equals(httpRequest
						.getHeader("X-Requested-With"))) {
					ResultBean rb = new ResultBean();
					rb.setSuccess(false);
					rb.setMsg("登录过期，请重新登录！");
					rb.setStatus(-1);
					ResponseUtils.renderJson(httpResponse,
							JSON.toJSONString(rb));
					return;
				}
				// String toUrl = httpRequest.getRequestURL().toString();
				// if (!StringUtils.isBlank(httpRequest.getQueryString())) {
				// toUrl += "?" + httpRequest.getQueryString();
				// }
				// ②-4将用户的请求URL保存在session中，用于登录成功之后，跳到目标URL
				// httpRequest.getSession().setAttribute("toUrl", toUrl);
				// 顶层窗口跳转到登录页
				String loginUrl = request.getServletContext().getContextPath()
						+ "/login.jsp";
				String script = "<script type='text/javascript'>window.top.location='"
						+ loginUrl + "'</script>";
				response.getWriter().write(script);
				// ②-5转发到登录页面
				// request.getRequestDispatcher("/login.jsp").forward(request,
				// response);
				return;
			}
			chain.doFilter(request, response);
		}
	}

	/**
	 * 当前URI资源是否需要登录才能访问
	 * 
	 * @param requestURI
	 * @param request
	 * @return
	 */
	private boolean isURILogin(String requestURI, HttpServletRequest request) {
		if (request.getContextPath().equalsIgnoreCase(requestURI)
				|| (request.getContextPath() + "/")
						.equalsIgnoreCase(requestURI)) {
			return false;
		}
		for (String uri : INHERENT_ESCAPE_URIS) {
			if (requestURI != null && requestURI.indexOf(uri) >= 0) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
